#!/usr/bin/env python
# -*- coding: utf-8 -*-
# time: 2022/10/19 15:11
# file: user.py
# author: lotus163
# 岗位没有数据权限的问题
from typing import Optional

from fastapi import APIRouter, Depends

from ...core.datascope import DataScope
from ...core.deps import UserDepends, get_user_depends
from ...core.result import Result, result_success, ResultData, ResultList
from ...crud import PostDao
from ...schemas import SysPostSch
from ...schemas.system.post import SysPostAdd
from ...utils.form_util import get_form_dict
from ...utils.string_util import get_array_by_str

router = APIRouter(prefix="/post", tags=["岗位"])


@router.put("", response_model=Result, summary='修改岗位')
async def update_post(form: SysPostSch, user_depends: UserDepends = Depends(get_user_depends)):
    post_db = await PostDao.get_db_or_none(postId=form.postId)
    form.updateBy = user_depends.login_user.user.userName
    await PostDao.update_sch(obj=post_db, **form.dict(exclude_none=True))
    return result_success()


@router.post("", response_model=Result, summary='新增岗位')
async def add_post(form: SysPostAdd, user_depends: UserDepends = Depends(get_user_depends)):
    # 无数据权限
    form.createBy = user_depends.login_user.user.userName
    await PostDao.add_sch(**form.dict(exclude_none=True))
    return result_success()


@router.post("/export", response_model=Result, summary='导出岗位列表')
async def export_posts():
    pass


@router.get("/list", response_model=ResultList[SysPostSch], summary='获取岗位列表')
async def get_posts_list(pageNum: int, pageSize: int,
                         postName: Optional[str] = None,
                         postCode: Optional[str] = None,
                         status: Optional[str] = None,
                         user_depends: UserDepends = Depends(get_user_depends)):
    request = user_depends.request_service.request
    # 准备查询的参数
    form_dict = get_form_dict(form=SysPostSch(postName=postName, postCode=postCode, status=status))
    # 查询
    posts_sch = await PostDao.get_list_sch_page(pageSize=pageSize, pageNum=pageNum, **form_dict)
    total = await PostDao.get_list_count(**form_dict)
    return result_success(msg="查询成功", rows=posts_sch, total=total)


@router.delete("/{postIds}", response_model=Result, summary='根据ids删除岗位')
async def remove_posts(postIds: str, user_depends: UserDepends = Depends(get_user_depends)):
    await PostDao.delete_db(postId__in=get_array_by_str(postIds))
    return result_success()


@router.get("/{postId}", response_model=ResultData, summary='根据岗位编号获取详细信息')
async def get_post_info(postId: int, user_depends: UserDepends = Depends(get_user_depends)):
    request = user_depends.request_service.request
    post_sch = await PostDao.get_sch_or_none(postId=postId)
    return result_success(data=post_sch)
